<?php

namespace APP\Ctrl;
use CMS\Ctrl as Base;
use CMS\Helper as Helper;

class Index extends Base {
	private $announcement;

	// construct
	public function run() {
		$this->view->title = $this->settings['blizz_guild'] . ' - Home';

		// get applications category id
		$this->announcement = $this->db->querySingle("SELECT id FROM categories WHERE type = 1 ORDER BY position ASC");
		if(is_null($this->announcement))
			die(new Error());

		// manage uri paths
		@list($page) = $this->uri;
		$this->index($page ? $page : 0);
	}

	// get the news
	public function index($page) {
		$this->view->func = 'index';

		// prepare vars
		$page = $this->db->escapeString((int)$page);

		// count topics
		$count = $this->db->querySingle("SELECT COUNT(id) as nr FROM topics WHERE category = " . $this->announcement);
		$lastpage = ceil($count / $this->settings['nav_news']);
		if($page < 1) $page = 1;
		if($page > $lastpage) $page = $lastpage;
		$this->view->pagination = Helper::paginate($lastpage, $page);
		$limit = $count ? ('LIMIT ' .($page - 1) * $this->settings['nav_news'] .',' . $this->settings['nav_news']) : null;

		// find the topics
		$result = $this->db->query("SELECT
			t.id, t.name,
			r.author, r.message, r.time,
			a.id AS author_id, a.email As author_email, a.name As author_name,
			COUNT(p.id) AS comments

			FROM topics AS t
			LEFT JOIN replies AS r ON r.topic = t.id AND r.starter = 1
			LEFT JOIN users AS a ON r.author = a.id
			LEFT JOIN replies AS p ON p.topic = t.id AND p.starter = 0

		WHERE t.category = {$this->announcement}
		GROUP BY t.id
		ORDER BY r.time DESC {$limit}");

		// transform
		$data = array();
		while($res = $result->fetchArray(SQLITE3_ASSOC)) {
			$lastpage = ceil(($res['comments'] + 1) / $this->settings['nav_replies']);

			$data[] = array(
				'name' => $res['name'],
				'link' => $res['id'] . '-' . Helper::generate_named_id($res['name']),
				'author_id' => $res['author_id'],
				'author_avatar' => md5(strtolower($res['author_email'])),
				'author_name' => $res['author_name'],
				'author_link' => $res['author_id'] . '-' . Helper::generate_named_id($res['author_name']),
				'time' => Helper::format_time($res['time']),
				'comments' => $res['comments'],
				'comments_link' => $res['id'] . '-' . Helper::generate_named_id($res['name']) . ($lastpage != 1 ? '/' . $lastpage : ''),
				'message' => Helper::format_message($res['message'])
			);
		}

		// output data
		$this->view->data = $data;

		// set path
		$this->view->path = array(
			'func' => $this->view->func,
			'page' => (int)$page
		);
	}
}